package com.syx.friend.Service.Impl;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.syx.commoncore.Constant.Constant;
import com.syx.commoncore.Model.PageQueryDTO;
import com.syx.commoncore.Model.TableDataInfoResult;
import com.syx.commoncore.Utils.ThreadLocalUtil;
import com.syx.friend.Manager.MessageCacheManager;
import com.syx.friend.Mapper.MessageTextMapper;
import com.syx.friend.Model.message.VO.MessageTextVO;
import com.syx.friend.Service.IUserMessageService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class IUserMessageServiceImpl implements IUserMessageService {

    @Resource
    MessageCacheManager messageCacheManager;

    @Resource
    MessageTextMapper messageTextMapper;



    @Override
    public TableDataInfoResult list(PageQueryDTO pageQueryDTO) {
        Long userId = ThreadLocalUtil.get(Constant.USER_ID, Long.class);
        Long total = messageCacheManager.getListSize(userId);
        List<MessageTextVO> messageTextVOList;
        if (total == null || total <= 0) {
            //从数据库中查询我的竞赛列表
            PageHelper.startPage(pageQueryDTO.getPageNum(), pageQueryDTO.getPageSize());
            messageTextVOList = messageTextMapper.selectUserMsgList(userId);
            //为空的话进行刷新缓存
            messageCacheManager.refreshCache(userId);
            total = new PageInfo<>(messageTextVOList).getTotal();
        } else {
            messageTextVOList = messageCacheManager.getMsgTextVOList(pageQueryDTO, userId);
        }
        if (CollectionUtil.isEmpty(messageTextVOList)) {
            return TableDataInfoResult.empty();
        }
        return TableDataInfoResult.success(messageTextVOList, total);
    }
    }

